﻿/* 
 * LogonOptionsControl.cs
 * 
 * Author - Ankit Gupta and Gaurav Aggarwal
 * 
 * This file acts as a controller to Logon Options tab.
 * 
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Security;
using System.Diagnostics;

partial class LogonOptionsControl : UserControl
{
    // Apply the changes
    private void applyButton_Click(object sender, EventArgs e)
    {   
        // Validate wheteher input is in desired format or not
        if (validatedata() == false)
            return;
        
        // Preserve Tokens
        if (preserveTokensCheckBox.Checked)
        {
            serviceParameters.SetValue("LogoffPreserveTokens", 1, RegistryValueKind.DWord);
        }
        else
        {
            serviceParameters.DeleteValue("LogoffPreserveTokens", false);
        }
        
        node = datagrid.CurrentCell.Value.ToString();

        if (!node.Equals("Default"))
        {
            selectedDomain = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Services\\TransarcAFSDaemon\\NetworkProvider\\Domain\\" + node, true);
            try
            {
                // Don't report any errors
                if (reportErrorsCheckBox.Checked)
                {
                    selectedDomain.SetValue("FailLoginsSilently", 1, RegistryValueKind.DWord);
                }
                else
                {
                    selectedDomain.DeleteValue("FailLoginsSilently", false);
                }

                // Retry every
                if ("30".Equals(retryEveryTextBox.Text))
                {
                    selectedDomain.DeleteValue("LoginRetryInterval", false);
                }
                else
                {
                    selectedDomain.SetValue("LoginRetryInterval", Int32.Parse(retryEveryTextBox.Text), RegistryValueKind.DWord);
                }

                // Quit after
                if ("5".Equals(quitAfterTextBox.Text))
                {
                    selectedDomain.DeleteValue("LoginSleepInterval", false);
                }
                else
                {
                    selectedDomain.SetValue("LoginSleepInterval", Int32.Parse(quitAfterTextBox.Text), RegistryValueKind.DWord);
                }

                // Logon Script
                if ("".Equals(logonScriptTextBox.Text))
                {
                    selectedDomain.DeleteValue("LogonScript", false);
                }
                else
                {
                    selectedDomain.SetValue("LogonScript", logonScriptTextBox.Text, RegistryValueKind.ExpandString);
                }

               
            }
            catch (SecurityException)
            {
                MessageBox.Show("You do not have access to apply these settings.", "Access Denied", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        else
        {
            try
            {
                // Don't report any errors
                if (reportErrorsCheckBox.Checked)
                {
                   netprovider.SetValue("FailLoginsSilently", 1, RegistryValueKind.DWord);
                }
                else
                {
                    netprovider.DeleteValue("FailLoginsSilently", false);
                }

                // Retry every
                if ("30".Equals(retryEveryTextBox.Text))
                {
                    netprovider.DeleteValue("LoginRetryInterval", false);
                }
                else
                {
                    netprovider.SetValue("LoginRetryInterval", Int32.Parse(retryEveryTextBox.Text), RegistryValueKind.DWord);
                }

                // Quit after
                if ("5".Equals(quitAfterTextBox.Text))
                {
                    netprovider.DeleteValue("LoginSleepInterval", false);
                }
                else
                {
                    netprovider.SetValue("LoginSleepInterval", Int32.Parse(quitAfterTextBox.Text), RegistryValueKind.DWord);
                }

                // Logon Script
                if ("".Equals(logonScriptTextBox.Text))
                {
                    netprovider.DeleteValue("LogonScript", false);
                }
                else
                {
                    netprovider.SetValue("LogonScript", logonScriptTextBox.Text, RegistryValueKind.ExpandString);
                }
            }
            catch (SecurityException)
            {
                MessageBox.Show("You do not have access to apply these settings.", "Access Denied", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

    // Cancel the operations
    private void cancelButton_Click(object sender, EventArgs e)
    {
        Process[] p = Process.GetProcessesByName("mmc");
        p[0].Kill();
    }

    // Update cells
    private void updateButton_Click(object sender, EventArgs e)
    {
        node = datagrid.CurrentCell.Value.ToString();
        if(!node.Equals("Default"))
        {
            selectedDomain = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Services\\TransarcAFSDaemon\\NetworkProvider\\Domain\\" + node, true);
            String cells = selectedDomain.GetValue("TheseCells", "").ToString();

            if ("".Equals(cellsTextBox.Text))
            {
                selectedDomain.DeleteValue("TheseCells", false);
            }
            else
            {
                Array a = cells.Split(',');
                Array b = cellsTextBox.Text.Split(',');
                int i, j;
                for (i = 0; i < a.Length; i++)
                {
                    for (j = 0; j < b.Length; j++)
                    {
                        if (b.GetValue(j).ToString() == "," || b.GetValue(j).ToString().Equals(a.GetValue(i).ToString()))
                            b.SetValue("", j);
                    }
                }
                String t = "";
                for(i=0;i<b.Length;i++)
                {
                    if (b.GetValue(i).ToString() != "")
                    {
                        t += b.GetValue(i).ToString() + ",";
                    }
                }
                if (t.Length > 0)
                    t = t.Substring(0, t.Length - 1);
                else
                    t = "";
                if (cells != "")
                    cells += ",";
                cells += t;
                selectedDomain.SetValue("TheseCells", cells, RegistryValueKind.ExpandString);
                cellsTextBox.Text = cells;
            }
        }
        else 
        {
            String cells = netprovider.GetValue("TheseCells", "").ToString();

            if ("".Equals(cellsTextBox.Text))
            {
                netprovider.DeleteValue("TheseCells", false);
            }
            else
            {
                Array a = cells.Split(',');
                Array b = cellsTextBox.Text.Split(',');
                int i, j;
                for (i = 0; i < a.Length; i++)
                {
                    for (j = 0; j < b.Length; j++)
                    {
                        if (b.GetValue(j).ToString() == "," || b.GetValue(j).ToString().Equals(a.GetValue(i).ToString()))
                            b.SetValue("", j);
                    }
                }
                String t = "";
                for (i = 0; i < b.Length; i++)
                {
                    if (b.GetValue(i).ToString() != "")
                    {
                        t += b.GetValue(i).ToString() + ",";
                    }
                }
                if (t.Length > 0)
                    t = t.Substring(0, t.Length - 1);
                else
                    t = "";
                if (cells != "")
                    cells += ",";
                cells += t;
               netprovider.SetValue("TheseCells", cells, RegistryValueKind.ExpandString);
               cellsTextBox.Text = cells;
            }
        }
    }

    // Remove cells
    private void removeButton_Click(object sender, EventArgs e)
    {
        String cells;
        node = datagrid.CurrentCell.Value.ToString();
        if (!node.Equals("Default"))
        {
             selectedDomain = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Services\\TransarcAFSDaemon\\NetworkProvider\\Domain\\" + node, true);
             cells = selectedDomain.GetValue("TheseCells").ToString();
        }
        else 
        {
            cells = netprovider.GetValue("TheseCells").ToString();
        }
        
        Array a = cells.Split(',');
        String rem = cellsTextBox.Text;
        Array b = rem.Split(',');

        for (int i = 0; i < b.Length; i++)
        {
             for (int j = 0; j < a.Length; j++)
             {
                if (a.GetValue(j).ToString() == "," || a.GetValue(j).ToString().Equals(b.GetValue(i)))
                    a.SetValue("", j);
             }
        }
        cells = "";
        for (int i = 0; i < a.Length; i++)
        {
            if (a.GetValue(i).ToString() != "")
            {
                 cells += a.GetValue(i).ToString() + ",";
             }
        }
        if (cells.Length > 0)
            cells = cells.Substring(0, cells.Length - 1);
        else
            cells = "";

        if (!node.Equals("Default"))
            selectedDomain.SetValue("TheseCells", cells, RegistryValueKind.ExpandString);
        else
            netprovider.SetValue("TheseCells", cells, RegistryValueKind.ExpandString);

        cellsTextBox.Text = cells;
    }

    // Add new domain
    private void newDomain_Click(object sender, EventArgs e)
    {
        if(newDomainTextBox.Text.Equals(""))
        {
            String error = "New Domain should be a non-empty string";
            MessageBox.Show(error);
            return;
        }

        RegistryKey newDomainName = Registry.LocalMachine.CreateSubKey("SYSTEM\\CurrentControlSet\\Services\\TransarcAFSDaemon\\NetworkProvider\\Domain\\" + newDomainTextBox.Text);

        RegistryKey domain = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Services\\TransarcAFSDaemon\\NetworkProvider\\Domain\\", true);
        Array a = null;
        if (domain != null) a = domain.GetSubKeyNames();

        datagrid.Rows.Clear();
        datagrid.Rows.Add("Default");
        if (a != null)
        {
            for (int i = 0; i < a.Length; i++)
            {
                datagrid.Rows.Add(a.GetValue(i).ToString());
            }
        }

        newDomainName.SetValue("FailLoginsSilently", Convert.ToBoolean((int)netprovider.GetValue("FailLoginsSilently", 0)),RegistryValueKind.DWord);
        newDomainName.SetValue("LoginRetryInterval", ((int)netprovider.GetValue("LoginRetryInterval", 30)).ToString(),RegistryValueKind.DWord);
        newDomainName.SetValue("LoginSleepInterval",((int)netprovider.GetValue("LoginSleepInterval", 5)).ToString(),RegistryValueKind.DWord);
        newDomainName.SetValue("LogonScript",netprovider.GetValue("LogonScript", "").ToString());
        newDomainName.SetValue("TheseCells",netprovider.GetValue("TheseCells", "").ToString());

    }

    private void datagridView_Click(object sender, EventArgs e)
    {
        if (datagrid.CurrentCell.Value == null)
            return;
        node = datagrid.CurrentCell.Value.ToString();
        grpbox1.Text = "Logon Options for " + node;
        if (!node.Equals("Default"))
        {
            selectedDomain = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Services\\TransarcAFSDaemon\\NetworkProvider\\Domain\\" + node, true);
            reportErrorsCheckBox.Checked = Convert.ToBoolean((int)selectedDomain.GetValue("FailLoginsSilently", 0));
            retryEveryTextBox.Text = ((int)selectedDomain.GetValue("LoginRetryInterval",30)).ToString();
            quitAfterTextBox.Text = ((int)selectedDomain.GetValue("LoginSleepInterval", 5)).ToString();
            logonScriptTextBox.Text = selectedDomain.GetValue("LogonScript", "").ToString();
            cellsTextBox.Text = selectedDomain.GetValue("TheseCells", "").ToString();
        }
        else
        {
            reportErrorsCheckBox.Checked = Convert.ToBoolean((int)netprovider.GetValue("FailLoginsSilently", 0));
            retryEveryTextBox.Text = ((int)netprovider.GetValue("LoginRetryInterval", 30)).ToString();
            quitAfterTextBox.Text = ((int)netprovider.GetValue("LoginSleepInterval", 5)).ToString();
            logonScriptTextBox.Text = netprovider.GetValue("LogonScript", "").ToString();
            cellsTextBox.Text = netprovider.GetValue("TheseCells", "").ToString();
        }       
    }

    // Error checking
    private bool validatedata()
    {
        if (!checkint(retryEveryTextBox.Text))
        {
            String error = "Retry Every interval should be an integer";
            MessageBox.Show(error);
            return false;
        }
        if (!checkint(quitAfterTextBox.Text))
        {
            String error = "Quit After interval should be an integer";
            MessageBox.Show(error);
            return false;
        }

        if (logonScriptTextBox.Text.Equals(""))
        {
            String error = "Logon Script should not be a non-empty string";
            MessageBox.Show(error);
            return false;
        }
        return true;
    }        
   
    private bool checkint(string a)
    {
        bool flag = true;

        if (a.Equals("")) flag = false;

        for (int i = 0; i < a.Length; i++)
        {
            if (a[i] < 48 || a[i] > 57) flag = false;
        }
        return flag;
    }
}